/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejercicio.practica7;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author manolo
 */
public class Servidor {

    private ThreadPoolExecutor executor;

    public Servidor() {
        executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();//Crea el objeto executor o un pool de threads  
    }

    public void ejecutaTarea(Tarea tarea) {
        executor.execute(tarea);// Ejecuta una tarea 
    }

    public void terminaServidor() {
        executor.shutdown();// Este metodo termina el executor  
    }

    public static class Tarea implements Runnable {

        private String nombre;

        public Tarea(String nombre) {
            this.nombre = nombre;
        }

        public void run() {
            System.out.println(Thread.currentThread().getName() + ", creado: " + new Date());
            try {
                TimeUnit.SECONDS.sleep((long) (Math.random() * 10));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ", terminado: " + new Date());
        }

    }

    public static void main(String[] args) {
        Servidor servidor = new Servidor();
        for (int i = 0; i < 10; i++) {
            Tarea tarea = new Tarea("Tarea " + i);
            servidor.ejecutaTarea(tarea);
        }
        servidor.terminaServidor();
    }
}
